/*
 * Copyright (c) 2012 SUBSECRETARIA DEFENSORIA DEL ESPACIO PUBLICO - SDEP.
 * All Rights Reserved.
 * This software is the confidential and proprietary information of SDEP
 * Developed By CONSTULT-SOFT S.A, Development Team 2012.
 *
 */
package co.gov.medellin.sdep.sisdep.domain.operativa;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;

import co.gov.medellin.sdep.sisdep.operativa.exception.ComparendoException;
import co.gov.medellin.sdep.sisdep.operativa.exception.ComparendoRuntimeException;
import co.gov.medellin.sdep.sisdep.operativa.service.IComparendoNegReinService;
import co.gov.medellin.sdep.sisdep.operativa.service.IComparendoSegContService;
import co.gov.medellin.sdep.sisdep.operativa.service.IComparendoService;
import co.gov.medellin.sdep.sisdep.operativa.service.IRemisionService;
import co.gov.medellin.sdep.sisdep.regulacion.exception.FeriaDecFormVentaException;
import co.gov.medellin.sdep.sisdep.common.AppConstants;
import co.gov.medellin.sdep.sisdep.common.OracleHelper;
import co.gov.medellin.sdep.sisdep.domain.MessageModalWindowController;
import co.gov.medellin.sdep.sisdep.domain.BaseController;
import co.gov.medellin.sdep.sisdep.integration.mapasmedellin.BeanDireccion;
import co.gov.medellin.sdep.sisdep.integration.mapasmedellin.GeoUbicacionClient;
import co.gov.medellin.sdep.sisdep.model.Comparendo;
import co.gov.medellin.sdep.sisdep.model.FeriaDecembrinaForm;
import co.gov.medellin.sdep.sisdep.model.Persona;

/**
 * @author Usuario
 * 
 */
public class ComparendoController extends BaseController implements
		Serializable {

	/**
	 * generated serial version
	 */
	private static final long serialVersionUID = -3285110767384990403L;

	/**
	 * Constructor por defecto, inicializa los elemento basicos del Controlador
	 */
	public ComparendoController() {
		this.comparendoListModel = new ListDataModel();
	}

	/** bean para el manejo del formulario de busqueda Comparendo */
	public Comparendo comparendoSearch = new Comparendo();

	/** Objeto contenedor del listado de Comparendo luego de una consulta. */
	private DataModel comparendoListModel;

	/** bean para el manejo del formulario de creacion/edicion. Comparendo */
	private Comparendo comparendo = new Comparendo();

	/** instancia de servicio comparendoService */
	private IComparendoService comparendoService;
	
	/** instancia de servicio feriaDecFormVentaService */
	private List listaInfracciones;

	ComparendoNegReinController comparendoNegReinController ;
	
	ComparendoSegContController comparendoSegContController ;
	
	RemisionController remisionController ;
	
	private Persona personaLocal = new Persona();
	
	private GeoUbicacionClient geoUbicacionClient;	

	/** instancia un objeto de direccion local, en caso que el usuario no valide direccion al menos una vez */
	private BeanDireccion direccionLocal = new BeanDireccion();
	// --------------------------------------------------------------------
	// --- metodos para atender acciones init()
	// --------------------------------------------------------------------



	/**
	 * 
	 * @return String
	 */
	public String searchComparendoByKey() {
		String msg = "";
		try {
			List valores = null;
			valores = getComparendoService().load(1, 10,
					this.comparendoSearch);
			this.comparendoListModel.setWrappedData(valores);
		} catch (Exception e) {
			msg = e.getMessage();
			e.printStackTrace(System.err);
		}
		if (this.comparendoListModel.getWrappedData() == null) {
			msg = AppConstants.NO_RECORDS_FOUND;
		} else {
			if (((List) this.comparendoListModel.getWrappedData()).isEmpty()) {
				msg = AppConstants.NO_RECORDS_FOUND;
			}
		}
		((MessageModalWindowController) getBean("messageController"))
				.setSuccessMessage(msg, null, null);
		return AppConstants.COMPARENDO_SEARCH_VIEW;
	}

	/**
	 * 
	 * @return String
	 */
	public String searchComparendoByRadicado() {
		String msg = "";
		try {
			List valores = null;
			valores = getComparendoService().loadByRadicado(1, 10,
					this.comparendoSearch);
			this.comparendoListModel.setWrappedData(valores);
		} catch (Exception e) {
			msg = e.getMessage();
			e.printStackTrace(System.err);
		}
		if (this.comparendoListModel.getWrappedData() == null) {
			msg = AppConstants.NO_RECORDS_FOUND;
		} else {
			if (((List) this.comparendoListModel.getWrappedData()).isEmpty()) {
				msg = AppConstants.NO_RECORDS_FOUND;
			}
		}
		((MessageModalWindowController) getBean("messageController"))
				.setSuccessMessage(msg, null, null);
		return AppConstants.COMPARENDO_SEARCH_VIEW;
	}
	
	/**
	 * 
	 * @return
	 */
	public String create() {
		String msg = AppConstants.DEFAULT_ERROR;
		try {
			if (this.comparendo.getId().longValue() == 0L) {
				if(getComparendoService().verificarDocumento(comparendo).equals("1")){	
					comparendo.setIdComparendoEntidad(new Long(comparendo.getIdComparendoEntidadStr()));
					comparendo.setIdTipoInfraccion(new Long(comparendo.getIdTipoInfraccionStr()));
					comparendo.setIdTipoInfractor(new Long(comparendo.getIdTipoInfractorStr()));
					if(comparendo.isCobroCoactivoChk())
						comparendo.setCobroCoactivo("S");
					else
						comparendo.setCobroCoactivo("N");
					if(comparendo.getValorCobroStr() == null || comparendo.getValorCobroStr().equals(""))
						comparendo.setValorCobro(new Long(0));
					else
						comparendo.setValorCobro(new Long(comparendo.getValorCobroStr()));
					
					getComparendoService().insert(this.comparendo);
					msg = AppConstants.SUCCESS_CREATE;
				}else{
					msg = "El Documento Ingresado no existe en el sistema, Por favor registre la persona";
					((MessageModalWindowController) getBean("messageController"))
					.setSuccessMessage("  " + msg, null, null);
					return AppConstants.COMPARENDO_CREATE_VIEW;
				}
			}
		} catch (ComparendoException e) {
			msg = e.getEndUserMessage();
			e.printStackTrace(System.err);
		} catch (ComparendoRuntimeException e) {
			msg = e.getEndUserMessage();
			e.printStackTrace(System.err);
		}
		((MessageModalWindowController) getBean("messageController"))
				.setSuccessMessage("- comparendo " + msg, null, null);
		return AppConstants.COMPARENDO_SEARCH_VIEW;
	}

	/**
	 * 
	 * @return
	 */
	public String update() {
		String msg = AppConstants.DEFAULT_ERROR;
		try {
			if (this.comparendo.getId().longValue() != 0L) {
				if(getComparendoService().verificarDocumento(comparendo).equals("1")){
					comparendo.setIdComparendoEntidad(new Long(comparendo.getIdComparendoEntidadStr()));
					comparendo.setIdTipoInfraccion(new Long(comparendo.getIdTipoInfraccionStr()));
					comparendo.setIdTipoInfractor(new Long(comparendo.getIdTipoInfractorStr()));
					if(comparendo.isCobroCoactivoChk())
						comparendo.setCobroCoactivo("S");
					else
						comparendo.setCobroCoactivo("N");
					if(comparendo.getValorCobroStr() == null || comparendo.getValorCobroStr().equals(""))
						comparendo.setValorCobro(new Long(0));
					else
						comparendo.setValorCobro(new Long(comparendo.getValorCobroStr()));
					
					getComparendoService().update(this.comparendo);
					msg = AppConstants.SUCCESS_UPDATE;
				}else{
					msg = "El Documento Ingresado no existe en el sistema, Por favor registre la persona";
					((MessageModalWindowController) getBean("messageController"))
					.setSuccessMessage("  " + msg, null, null);
					return AppConstants.COMPARENDO_UPDATE_VIEW;
				}
			}
		} catch (ComparendoException e) {
			msg = e.getEndUserMessage();
			e.printStackTrace(System.err);
		} catch (ComparendoRuntimeException e) {
			msg = e.getEndUserMessage();
			e.printStackTrace(System.err);
		}
		((MessageModalWindowController) getBean("messageController"))
				.setSuccessMessage("- Valor Tipo Maestra " + msg, null, null);
		return AppConstants.COMPARENDO_SEARCH_VIEW;
	}
	
	public String checkAddress() {
		direccionLocal = getGeoUbicacionClient().getAddressLocalization(this.comparendo.getDireccion());
		if(null == direccionLocal) {
			direccionLocal = new BeanDireccion();
		}
		comparendo.setCodigoBarrio(OracleHelper.isNullorEmpty(direccionLocal.getCodBarrio()) ? "N/A" : direccionLocal.getCodBarrio());
		comparendo.setBarrio(OracleHelper.isNullorEmpty(direccionLocal.getValueNomBarrio()) ? "NO Disponible" : direccionLocal.getValueNomBarrio());
		comparendo.setCodigoComuna(OracleHelper.isNullorEmpty(direccionLocal.getCodComuna()) ? "N/A" : direccionLocal.getCodComuna());
		comparendo.setComuna(OracleHelper.isNullorEmpty(direccionLocal.getValueNomComuna()) ? "NO Disponible" : direccionLocal.getValueNomComuna());

		return "";
	}
	
	public List listaInfracciones() throws FeriaDecFormVentaException{
		List lstInfracciones = null;
		try{
			lstInfracciones = getComparendoService().listaInfracciones();
		} catch (Exception e) {
			e.printStackTrace(System.err);
		}
		return lstInfracciones;
		
	}
	
	// --------------------------------------------------------------------
	// --- metodos para atender acciones end()
	// --------------------------------------------------------------------

	// --------------------------------------------------------------------
	// --- metodos para atender reglas de navegacion init()
	// --------------------------------------------------------------------

	/**
	 * @throws FeriaDecFormVentaException 
	 * 
	 */
	public String createComparendo() throws FeriaDecFormVentaException {
		comparendo = new Comparendo();
		comparendo.setId(new Long(0L));
		comparendo.setCodigo("");
		comparendo.setIdCitacion(comparendoSearch.getIdCitacion());
		comparendo.setIdTipoDocumentoStr(comparendoSearch.getIdTipoDocumentoStr());
		comparendo.setDocumento(comparendoSearch.getDocumento());
		//comparendo.setValor("");
		//comparendo.setActivo("N");
		listaInfracciones = new ArrayList();
		if(listaInfracciones() != null){
			for(int i = 0; i<listaInfracciones().size();i++){			
				List listaT = new ArrayList();
				String registro[];
				listaT = (List)listaInfracciones().get(i);	
				registro = (String[])listaT.get(0);
				listaInfracciones.add(new SelectItem(registro[0].toString(),registro[1].toString()));
				listaT = null;
				registro=null;
			}
			checkAddress();			
		}
		return AppConstants.COMPARENDO_CREATE_VIEW;
	}

	/**
	 * 
	 * @return
	 * @throws FeriaDecFormVentaException 
	 */
	public String updateComparendo() throws FeriaDecFormVentaException {
		Map params = getExternalContext().getRequestParameterMap();
		String comparendoDataIndex = (String) params
				.get("comparendoDataIndex");
		this.comparendo = (Comparendo) ((List) this.comparendoListModel
				.getWrappedData())
				.get(Integer.parseInt(comparendoDataIndex));
		listaInfracciones = new ArrayList();
		if(listaInfracciones() != null){
			for(int i = 0; i<listaInfracciones().size();i++){			
				List listaT = new ArrayList();
				String registro[];
				listaT = (List)listaInfracciones().get(i);	
				registro = (String[])listaT.get(0);
				listaInfracciones.add(new SelectItem(registro[0].toString(),registro[1].toString()));
				listaT = null;
				registro=null;
			}
			checkAddress();
		}
		return AppConstants.COMPARENDO_UPDATE_VIEW;
	}

	/**
	 * 
	 * @return
	 */
	public String negociacionComparendo() {
		Map params = getExternalContext().getRequestParameterMap();
		String comparendoDataIndex = (String) params
				.get("comparendoDataIndex");
		this.comparendo = (Comparendo) ((List) this.comparendoListModel
				.getWrappedData())
				.get(Integer.parseInt(comparendoDataIndex));
			
		getComparendoNegReinController().comparendoNegReinSearch.setRadicado(comparendo.getRadicado());
		getComparendoNegReinController().comparendoNegReinSearch.setIdComparendo(comparendo.getId());
		getComparendoNegReinController().searchComparendoNegReinByRadicado(getComparendoNegReinController().getComparendoNegReinService());		
		return AppConstants.COMPARENDO_NEG_REIN_SEARCH_VIEW;
	}
	
	/**
	 * 
	 * @return
	 */
	public String seguimientoComparendo() {
		Map params = getExternalContext().getRequestParameterMap();
		String comparendoDataIndex = (String) params
				.get("comparendoDataIndex");
		this.comparendo = (Comparendo) ((List) this.comparendoListModel
				.getWrappedData())
				.get(Integer.parseInt(comparendoDataIndex));
			
		getComparendoSegContController().comparendoSegContSearch.setRadicado(comparendo.getRadicado());
		getComparendoSegContController().comparendoSegContSearch.setIdComparendo(comparendo.getId());
		getComparendoSegContController().searchComparendoSegContByRadicado(getComparendoSegContController().getComparendoSegContService());	
		return AppConstants.COMPARENDO_SEG_CONT_SEARCH_VIEW;
	}
	/**
	 * 
	 * @return
	 */
	public String remisionComparendo() {
		Map params = getExternalContext().getRequestParameterMap();
		String comparendoDataIndex = (String) params
				.get("comparendoDataIndex");
		this.comparendo = (Comparendo) ((List) this.comparendoListModel
				.getWrappedData())
				.get(Integer.parseInt(comparendoDataIndex));
						
		getRemisionController().remisionSearch.setRadicado(comparendo.getRadicado());
		getRemisionController().remisionSearch.setIdComparendo(comparendo.getId());
		getRemisionController().searchRemisionByRadicado(getRemisionController().getRemisionService());		
		return AppConstants.REMISION_SEARCH_VIEW;
	}	
	
	/**
	 * 
	 * @return
	 */
	public String cancelComparendo() {
		return AppConstants.COMPARENDO_SEARCH_VIEW;
	}

	// --------------------------------------------------------------------
	// --- metodos para atender reglas de navegacion end()
	// --------------------------------------------------------------------

	// --------------------------------------------------------------------
	// --- getters and setters init()
	// --------------------------------------------------------------------

	/**
	 * 
	 */
	public Comparendo getComparendoSearch() {
		return comparendoSearch;
	}

	/**
	 * 
	 * @param comparendoSearch
	 */
	public void setcomparendoSearch(Comparendo comparendoSearch) {
		this.comparendoSearch = comparendoSearch;
	}

	/**
	 * 
	 * @return
	 */
	public DataModel getcomparendoListModel() {
		return comparendoListModel;
	}

	/**
	 * 
	 * @param comparendoListModel
	 */
	public void setcomparendoListModel(DataModel comparendoListModel) {
		this.comparendoListModel = comparendoListModel;
	}

	/**
	 * 
	 * @return
	 */
	public Comparendo getComparendo() {
		return comparendo;
	}

	/**
	 * 
	 * @param comparendo
	 */
	public void setcomparendo(Comparendo comparendo) {
		this.comparendo = comparendo;
	}

	/**
	 * obtencion del servicio comparendoService
	 * 
	 * @return
	 */
	public IComparendoService getComparendoService() {
		return comparendoService;
	}

	/**
	 * establecimiento del servicio comparendoService, la inyeccion de la
	 * dependencia la cubre SpringFramework
	 * 
	 * @param comparendoService
	 */
	public void setComparendoService(
			IComparendoService comparendoService) {
		this.comparendoService = comparendoService;
	}

	
	public List getListaInfracciones() {
		return listaInfracciones;
	}

	public void setListaInfracciones(List listaInfracciones) {
		this.listaInfracciones = listaInfracciones;
	}

	public GeoUbicacionClient getGeoUbicacionClient() {
		return geoUbicacionClient;
	}

	public void setGeoUbicacionClient(GeoUbicacionClient geoUbicacionClient) {
		this.geoUbicacionClient = geoUbicacionClient;
	}

	public ComparendoNegReinController getComparendoNegReinController() {
		return comparendoNegReinController;
	}

	public void setComparendoNegReinController(
			ComparendoNegReinController comparendoNegReinController) {
		this.comparendoNegReinController = comparendoNegReinController;
	}

	public ComparendoSegContController getComparendoSegContController() {
		return comparendoSegContController;
	}

	public void setComparendoSegContController(
			ComparendoSegContController comparendoSegContController) {
		this.comparendoSegContController = comparendoSegContController;
	}

	public RemisionController getRemisionController() {
		return remisionController;
	}

	public void setRemisionController(RemisionController remisionController) {
		this.remisionController = remisionController;
	}

	public void setComparendo(Comparendo comparendo) {
		this.comparendo = comparendo;
	}

	public Persona getPersonaLocal() {
		return personaLocal;
	}

	public void setPersonaLocal(Persona personaLocal) {
		this.personaLocal = personaLocal;
	}	
	
	// --------------------------------------------------------------------
	// --- getters and setters end()
	// --------------------------------------------------------------------

}
